﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.Services.Protocols;
using Core.Entity;
using System.IO;

namespace JsonWebTest
{
    public class MySoapExtension : SoapExtension
    {
        private Stream oldStream;
        private Stream newStream;
        public override Stream ChainStream(Stream stream)
        {
            oldStream=stream;
            newStream=new MemoryStream();
            return newStream;
        }
        public override object GetInitializer(Type serviceType)
        {
            return GetType();
        }

        public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
        {
            return null;
        }

        public override void Initialize(object initializer)
        {
            
        }

        public override void ProcessMessage(SoapMessage message)
        {
            switch (message.Stage)
            {
                case SoapMessageStage.BeforeSerialize:
                    break;
                case SoapMessageStage.AfterSerialize:
                    newStream.Position = 0;
                    Copy(newStream, oldStream);
                    break;
                case SoapMessageStage.BeforeDeserialize:
                    Copy(oldStream, newStream);
                    newStream.Position = 0;
                    break;
                case SoapMessageStage.AfterDeserialize:
                    bool check = false;
                    break;
                default:
                    throw new Exception("invalid stage");
            }
        }

        private void Copy(Stream from, Stream to)
        {
            TextReader reader = new StreamReader(from);
            TextWriter writer = new StreamWriter(to);
            writer.WriteLine(reader.ReadToEnd());
            writer.Flush();
        }
    }
}
